package com.jl.smartcard.ui.views.cardlist;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

import opencard.core.terminal.CommandAPDU;
import opencard.core.terminal.ResponseAPDU;

import com.jl.card.Card;
import com.jl.card.parse.IAPDUComponent;
import com.jl.card.parse.part.APDUComponentManager;

public class TreeModel implements Card.CmdListenner{

	private List<IAPDUComponent> list = new LinkedList<IAPDUComponent>();
	private IAPDUComponent apduComponent;
	private CommandAPDU cmd;
	private SmartCardListView view;
	
	private ArrayBlockingQueue<IAPDUComponent> deque = new ArrayBlockingQueue<IAPDUComponent>(1024 * 10);
	public TreeModel(){
		new Thread(new Take()).start();
	}
	@Override
	public void onSend(CommandAPDU capdu) {
		cmd = capdu;
	}

	@Override
	public void onResponse(ResponseAPDU rapdu) {
		apduComponent = new APDUComponentManager(cmd, rapdu);
		try {
			deque.put(apduComponent);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public List<IAPDUComponent> getElements() {
		return list;
	}
	
	public void clear(){
		synchronized (this) {
			list.clear();
		}
	}

	public void setView(SmartCardListView smartCardListView) {
		this.view = smartCardListView;
	}
	
	private class Take implements Runnable{
		@Override
		public void run() {
			while (true) {
				try {
					IAPDUComponent val = deque.take();
					synchronized (this) {
						if(list.size() > 256){
							list.remove(list.size() - 1);
						}
						list.add(0, val);
						view.refreshTree();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
					return;
				}
			}
		
		}
		
	}

}
